﻿using System;
using System.Data;
using System.Web.UI;
using BLL;
using ET;
using Ext.Net;
using HTML;
using Roles;

namespace ERP.Modules
{
    public partial class Warehouse : UserControl
    {
        private readonly Warehouse_BLL clsWarehouse = new Warehouse_BLL();
        private readonly Branch_BLL _clsBranch = new Branch_BLL();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!X.IsAjaxRequest)
            {
                CheckPermisstion();
                GetBranch();
                GetData();
                ClearTextBox();
                GetComboBox();
                btnEdit.Disable(true);
                btnDel.Disable(true);
                btnExport.Disable(true);
                WindowsBranch();
            }
        }

        //-------Store-Datasource-----------------
        protected void StoreWarehouse_RefreshData(object sender, StoreReadDataEventArgs e)
        {
            txtSearch.Text = string.Empty;
            SelectBoxWarehouseBranch.Text = string.Empty;
            GetData();
            GetBranch();
        }

        //--------Buttom-Main------------------------
        protected void btnAddNew_Click(object sender, DirectEventArgs e)
        {
            GetComboBox();
            ClearTextBox();
            WindowsWarehouse.Show();
        }

        protected void btnEdit_Click(object sender, DirectEventArgs e)
        {
            var sm = grWarehouse.GetSelectionModel() as CheckboxSelectionModel;
            foreach (SelectedRow row in sm.SelectedRows)
            {
                GetComboBox();
                ClearTextBox();
                DataDetail(int.Parse(row.RecordID));
                WindowsWarehouse.Show();
                sm.UpdateSelection();
            }
        }

        protected void btnDel_Click(object sender, DirectEventArgs e)
        {
            var sm = grWarehouse.GetSelectionModel() as CheckboxSelectionModel;
            foreach (SelectedRow row in sm.SelectedRows)
            {
                try
                {
                    Warehouse_BLL.DeleteWarehouse(int.Parse(row.RecordID));
                }
                catch (Exception)
                {
                    clsFormat.Alert_ERROR("Thông Báo",
                        "Tồn tại tài liệu con, không xoá được vui lòng xoá tài liệu con trước !");
                }
            }
            GetData();
        }

        protected void SelectBoxWarehouseBranch_Change(object sender, DirectEventArgs e)
        {
            GetData();
        }
        //--------Buttom-Popup------------------------
        protected void btnSavePopUp_Click(object sender, DirectEventArgs e)
        {
            if (txtWarehouse_ID.Text == string.Empty)
            {
                InsertWarehouse();
            }
            else
            {
                if (CheckPermisstionDobclick())
                {
                    HTML.clsFormat.Alert_ERROR("Thông Báo", "Bạn không được cấp quyền để sửa đổi !");
                }
                else
                {
                    UpdateWarehouse();
                }
            }
        }

        protected void btnCancelPopUp_Click(object sender, DirectEventArgs e)
        {
            WindowsWarehouse.Close();
        }

        //----------Click-------------------
        protected void WarehouseDblClick(object sender, DirectEventArgs e)
        {
            GetComboBox();
            ClearTextBox();
            int Warehouse_Id = int.Parse(e.ExtraParams["Warehouse_Id"]);
            DataDetail(Warehouse_Id);
            WindowsWarehouse.Show();
        }

        #region[Method]

        protected void GetData()
        {
            if (String.IsNullOrEmpty(SelectBoxWarehouseBranch.Text))
            {
                DataTable dtWarehouse = clsWarehouse.Search(string.Empty);
                if (dtWarehouse != null && dtWarehouse.Rows.Count > 0)
                {
                    StoreWarehouse.DataSource = dtWarehouse;
                    StoreWarehouse.DataBind();
                }
            }
            else
            {
                DataTable dtWarehouse =
                    clsWarehouse.GetWarehouseFillter(int.Parse(SelectBoxWarehouseBranch.SelectedItem.Value));
                if (dtWarehouse != null && dtWarehouse.Rows.Count > 0)
                {
                    StoreWarehouse.DataSource = dtWarehouse;
                    StoreWarehouse.DataBind();
                }
            }
        }

        protected void DataDetail(int id)
        {
            DataTable dtWarehouse = clsWarehouse.GetWarehouseDetail_Edit(id);
            if (dtWarehouse != null && dtWarehouse.Rows.Count > 0)
            {
                txtWarehouse_ID.Text = dtWarehouse.Rows[0]["Warehouse_ID"].ToString();
                txtWarehouse_Alias.Text = dtWarehouse.Rows[0]["Warehouse_Alias"].ToString();
                txtWarehouse_Name.Text = dtWarehouse.Rows[0]["Warehouse_Name"].ToString();
                cbBranch.SetValue(int.Parse(dtWarehouse.Rows[0]["Branch_Id"].ToString()));
                txtWarehouse_Note.Text = dtWarehouse.Rows[0]["Warehouse_Note"].ToString();
            }
        }

        protected bool CheckInsert()
        {
            bool kiemtra = false;
            var clsWarehouse = new Warehouse_BLL();
            DataTable dtWarehouse = clsWarehouse.GetWarehouse();
            if (dtWarehouse != null && dtWarehouse.Rows.Count > 0)
            {
                foreach (DataRow dr in dtWarehouse.Rows)
                {
                    if (txtWarehouse_ID.Text != dr["Warehouse_ID"].ToString())
                    {
                        if (txtWarehouse_Alias.Text == dr["Warehouse_Alias"].ToString())
                        {
                            kiemtra = true;
                            clsFormat.Alert_ERROR("Thông Báo", "Mã kho đã tồn tại !");
                        }
                        else if (txtWarehouse_Name.Text == dr["Warehouse_Name"].ToString())
                        {
                            kiemtra = true;
                            clsFormat.Alert_ERROR("Thông Báo", "Tên kho đã tồn tại !");
                        }
                    }
                }
            }
            return kiemtra;
        }

        protected void InsertWarehouse()
        {
            try
            {
                if (!CheckInsert())
                {
                    var obj = new Warehouse_ET
                    {
                        Warehouse_Alias = txtWarehouse_Alias.Text,
                        Warehouse_Name = txtWarehouse_Name.Text,
                        Warehouse_Note = txtWarehouse_Note.Text,
                        Branch_Id = int.Parse(cbBranch.SelectedItem.Value)
                    };
                    Warehouse_BLL.InsertWarehouse(obj);
                    clsFormat.Alert_INFO("Thông Báo", "Thêm mới thành công !");
                    GetData();
                    ClearTextBox();
                }
            }
            catch (Exception ex)
            {
                clsFormat.Alert_ERROR("Lỗi", ex.ToString());
            }
        }

        protected void UpdateWarehouse()
        {
            try
            {
                if (!CheckInsert())
                {
                    var obj = new Warehouse_ET
                    {
                        Warehouse_Id = int.Parse(txtWarehouse_ID.Text),
                        Warehouse_Alias = txtWarehouse_Alias.Text,
                        Warehouse_Name = txtWarehouse_Name.Text,
                        Warehouse_Note = txtWarehouse_Note.Text,
                        Branch_Id = int.Parse(cbBranch.SelectedItem.Value)
                    };
                    Warehouse_BLL.UpdateWarehouse(obj);
                    WindowsWarehouse.Close();
                    clsFormat.Alert_INFO("Thông Báo", "Sữa thành công!");
                    GetData();
                    GetComboBox();
                }
            }
            catch (Exception ex)
            {
                clsFormat.Alert_ERROR("Lỗi", ex.ToString());
            }
        }

        private void GetBranch()
        {
            var _dtBranch = _clsBranch.GetBranch();
            if (_dtBranch != null && _dtBranch.Rows.Count > 0)
            {
                StoreWarehouseBranch.DataSource = _dtBranch;
                StoreWarehouseBranch.DataBind();
            }
            else
            {
                SelectBoxWarehouseBranch.GetStore().RemoveAll();
            }
        }
        #endregion

        #region [ComboBox]

        protected void GetComboBox()
        {
            var clsBranch = new Branch_BLL();
            DataTable dtBranch = clsBranch.Search(string.Empty);
            if (dtBranch != null && dtBranch.Rows.Count > 0)
            {
                BranchStore.DataSource = dtBranch;
                BranchStore.DataBind();
            }
        }

        protected void ReloadComboBox(object sender, StoreReadDataEventArgs e)
        {
            GetComboBox();
        }

        #endregion

        #region[ClearTextbox]

        protected void ClearTextBox()
        {
            FormPanelWarehouse.Reset();

            txtWarehouse_ID.Text = string.Empty;
            txtWarehouse_Alias.Text = MaTuDong();
            txtWarehouse_Name.Text = string.Empty;
            txtWarehouse_Note.Text = string.Empty;

            cbBranch.Clear();
        }

        #endregion

        #region[MaTangTuDong]

        protected string MaTuDong()
        {
            int i;
            DataTable dt = clsWarehouse.Search(string.Empty);
            if (dt != null && dt.Rows.Count > 0)
            {
                int max = int.Parse(dt.Rows[0]["Warehouse_ID"].ToString());
                for (i = 0; i < dt.Rows.Count; i++)
                {
                    if (int.Parse(dt.Rows[i]["Warehouse_ID"].ToString()) > max)
                    {
                        max = int.Parse(dt.Rows[i]["Warehouse_ID"].ToString());
                    }
                }
                i = max + 1;
            }
            else
            {
                i = 0;
            }
            return "K_00" + i;
        }

        #endregion

        #region[Search]

        protected void Search_Event(object sender, DirectEventArgs e)
        {
            DataTable dtWarehouse = clsWarehouse.Search(txtSearch.Text);
            if (dtWarehouse != null && dtWarehouse.Rows.Count > 0)
            {
                StoreWarehouse.DataSource = dtWarehouse;
                StoreWarehouse.DataBind();
            }
        }

        #endregion

        #region[Permisstion]
        private void CheckPermisstion()
        {
            if (Session["login"] != null && Session["USer_Detail_Id"].ToString() != string.Empty)
            {
                bool Is_BtnAdd;
                bool Is_BtnEdit;
                bool Is_BtnView;
                bool Is_BtnDel;
                bool Is_BtnPrint;
                bool Is_BtnCancel;
                bool Is_BtnReview;

                SecurityServices.HasPermisstion_Btn(StringContent.Warehouse, out Is_BtnAdd, out Is_BtnEdit, out Is_BtnDel, out Is_BtnView, out Is_BtnCancel, out Is_BtnPrint, out Is_BtnReview);
                if (Is_BtnAdd == false)
                {
                    btnAddNew.Visible = false;
                }
                if (Is_BtnEdit == false)
                {
                    btnEdit.Visible = false;
                }
                if (Is_BtnView == false)
                {
                    PanelWarehouse.Visible = false;
                }
                if (Is_BtnDel == false)
                {
                    btnDel.Visible = false;
                }
                if (Is_BtnPrint == false)
                {
                    btnExport.Visible = false;
                }
            }
        }
        private bool CheckPermisstionDobclick()
        {
            var check = false;
            if (Session["login"] != null && Session["USer_Detail_Id"].ToString() != string.Empty)
            {
                bool Is_BtnAdd;
                bool Is_BtnEdit;
                bool Is_BtnView;
                bool Is_BtnDel;
                bool Is_BtnPrint;
                bool Is_BtnCancel;
                bool Is_BtnReview;

                SecurityServices.HasPermisstion_Btn(StringContent.Warehouse, out Is_BtnAdd, out Is_BtnEdit, out Is_BtnDel, out Is_BtnView, out Is_BtnCancel, out Is_BtnPrint, out Is_BtnReview);
                if (Is_BtnEdit == false)
                {
                    check = true;
                }
            }
            return check;
        }
        #endregion
        //----------Button-Windows---------------
        private void WindowsBranch()
        {
            Window win = new Window()
            {
                ID = "WindowsBranch",
                Title = "Chi nhánh",
                Width = 829,
                Height = 400,
                Modal = true,
                AutoRender = false,
                Collapsible = false,
                Maximizable = true,
                Hidden = true,
                Loader = new ComponentLoader
                {
                    Url = "../PageParrent/Branch.aspx",
                    Mode = LoadMode.Frame,
                    LoadMask =
                    {
                        ShowMask = true
                    }
                }
            };
            this.Controls.Add(win);
        }
    }
}